from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu


# @index_blu.route('/news_list')
# def news_list():
#     # 获取参数
#     # 分类id
#     cid = request.args.get('cid', '1')
#     # 页数
#     page = request.args.get('page', '1')
#     # 每页多少条数据
#     per_page = request.args.get('per_page', '10')
#
#     # 校验参数
#     try:
#         cid = int(cid)
#         per_page = int(per_page)
#         page = int(page)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
#
#     # 查询数据
#     filters = []
#     if cid != 1:
#         filters.append(News.category_id == cid)
#     try:
#         paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
#         print(paginate)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg='查询错误')
#     # 取到当前页数
#     news_model_list = paginate.items
#     total_page = paginate.pages
#     current_page = paginate.page
#
#     news_dict_li = []
#     for news in news_model_list:
#         news_dict_li.append(news.to_basic_dict())
#
#     data = {
#         "total_page": total_page,
#         "current_page": current_page,
#         "news_dict_li": news_dict_li
#     }
#
#     return jsonify(errno=RET.OK, errmsg='OK', data=data)
@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """

    # 1. 获取参数
    # 新闻的分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数")

    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)

    # 3. 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取到当前页的数据
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blu.route('/')
def index():
    # 通过登陆刷新主页，将参数渲染到前段

    # 如果用户已经登陆,获取用户id，
    user_id = session.get('user_id', None)
    user = None
    if user_id:
        # 查询到用户后，查询该用户的数据
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.debug('e')

    # 右侧新闻的排行逻辑
    list_news = []
    try:
        list_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in list_news:
        news_dict_li.append(news)

    # 查询新闻分类，获取新闻
    categories = Category.query.all()

    categories_li = []
    for category in categories:
        categories_li.append(category.to_dict())

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "categories_li": categories_li
    }

    return render_template('news/index.html', data=data)


# 打开网页的时候浏览器会默认打开跟路由+favicon.con去加载网站标签小图标
@index_blu.route('/favicon.ico')
def favicon():
    # 如果有需要加载的静态文件，但是加载失败，就可以通过app应用
    # 里面的send_static_file 方法加载指定静态文件
    return current_app.send_static_file('news/favicon.ico')
